import { useState, useRef, useEffect } from "react";
import backgroundImage from "@/assets/p1/scenes/field-background.png";
import "./FieldSceneStyles.css";
import { history } from "umi";
import Character from "@/components/Character";
import Dog from "@/components/Dog";
import protagonistImage from "@/assets/p1/characters/protagonist-right.png";
import Dialog from "@/components/Dialog";
import dialogImage from "@/assets/p1/dialog_background_red.png";
import Card from "@/components/Card";
import familyHeadLeftImage from "@/assets/p1/characters/family-head-left.png";
import brother2LeftImage from "@/assets/p1/characters/brother2.png";
import TreasureBox from "@/components/TreasureBox";
import AchievementList from "@/components/AchievementList";
import { connect } from "umi";
import front1 from "@/assets/p1/front1.png";
import front2 from "@/assets/p1/front2.png";
import front3 from "@/assets/p1/front3.png";
import left1 from "@/assets/p1/left1.png";
import left2 from "@/assets/p1/left2.png";
import left3 from "@/assets/p1/left3.png";
import right1 from "@/assets/p1/right1.png";
import right2 from "@/assets/p1/right2.png";
import right3 from "@/assets/p1/right3.png";
import back1 from "@/assets/p1/back1.PNG";
import back2 from "@/assets/p1/back2.PNG";
import back3 from "@/assets/p1/back3.PNG";
import characterImage from "@/assets/p1/characters/protagonist.png";
import Map from "@/components/map"

const FieldChapterScene = ({ dispatch }) => {
	const screenWidth = window.innerWidth; // 1707
	const screenHeight = window.innerHeight; // 791

	const [isFainted, setIsFainted] = useState(true); // 人物初始为晕倒状态
	const [dogVisible, setDogVisible] = useState(false); // 狗狗初始不可见
	const [dogRunning, setDogRunning] = useState(false); // 狗狗跑步动画状态
	const [canMove, setCanMove] = useState(false);
	const [dogGoingHome, setDogGoingHome] = useState(false);
	const [showCard, setShowCard] = useState(false);
	const [dogX, setDogX] = useState(0.35 * screenWidth);
	const [dogY, setDogY] = useState(1.6 * screenHeight);
	const [showChatBubble, setShowChatBubble] = useState(false);
	const [dialogVisible, setDialogVisible] = useState(true);
	const [showCardBrother1Length, setShowCardBrother1Length] = useState(false);
	const [showCardBrother1Width, setShowCardBrother1Width] = useState(false);
	const [showCardBrother2Height, setShowCardBrother2Height] = useState(false);
	const [showCardBrother2Width, setShowCardBrother2Width] = useState(false);
	const [showCardBrother3UpWidth, setShowCardBrother3UpWidth] =
		useState(false);
	const [showCardBrother3BottomWidth, setShowCardBrother3BottomWidth] =
		useState(false);
	const [showCardBrother3Height, setShowCardBrother3Height] = useState(false);
	const [showTreasure, setShowTreasure] = useState(false);
	const [distance1Length, setDistance1Length] = useState(0);
	const [distance1Width, setDistance1Width] = useState(0);
	const [distance2Height, setDistance2Height] = useState(0);
	const [distance2Width, setDistance2Width] = useState(0);
	const [distance3UpWidth, setDistance3UpWidth] = useState(0);
	const [distance3BottomWidth, setDistance3BottomWidth] = useState(0);
	const [distance3Height, setDistance3Height] = useState(0);
	const [game, setGame] = useState(false);
	const [dialog1_1, setDialog1_1] = useState(false);
	const [dialog1, setDialog1] = useState(false);
	const [diaglog1_undone, setDialog1_undone] = useState(true);
	const [dialog2, setDialog2] = useState(false);
	const [dialog3, setDialog3] = useState(false);
	const [dialog4, setDialog4] = useState(false);
	const [dialog5, setDialog5] = useState(false);
	const [gouGuVisible, setGouGuVisible] = useState(false);
	const [inputBrother1, setInputBrother1] = useState("");
	const [inputBrother2, setInputBrother2] = useState("");
	const [inputBrother3, setInputBrother3] = useState("");
	const [fieldSuccess, setFieldSuccess] = useState(false);
	const [gouGuSuccess, setGouGuSuccess] = useState(false);
	const [finished, setFinished] = useState(false);

	// 角色初始位置是 initPositionX 和 initPositionY
	const initPositionX = 0.85 * screenWidth;
	const initPositionY = 1.6 * screenHeight;
	// 地的位置
	const xBrother1Width = 0.86 * screenWidth;
	const yBrother1Width = 0.77 * screenHeight;
	const xBrother1Length = 0.82 * screenWidth;
	const yBrother1Length = 0.96 * screenHeight;
	const xBrother2Width = 0.92 * screenWidth;
	const yBrother2Width = 1.02 * screenHeight;
	const xBrother2Height = 0.9 * screenWidth;
	const yBrother2Height = 1.24 * screenHeight;
	const xBrother3UpWidth = 0.72 * screenWidth;
	const yBrother3UpWidth = 0.95 * screenHeight;
	const xBrother3BottomWidth = 0.74 * screenWidth;
	const yBrother3BottomWidth = 1.32 * screenHeight;
	const xBrother3Height = 0.66 * screenWidth;
	const yBrother3Height = 1.15 * screenHeight;

	const [characterPosition, setCharacterPosition] = useState({
		x: initPositionX,
		y: initPositionY,
	});

	const dogRef = useRef();

	const characterImages = {
		front: [front1, front2, front3, front2],
		left: [left1, left2, left3, left2],
		right: [right1, right2, right3, right2],
		back: [back1, back2, back3, back2],
	};
	const handlePositionChange = newPosition => {
		setCharacterPosition(newPosition);
	};

	const dialogues = [
		"这里是哪里？",
		"这里是《九章算术》的世界，解锁完成《九章算术》内所有成就即可返回现实世界。",
		"每达成一个成就会获得线索，大黄可以帮你哦~",
		"",
	];
	const dialogues1_1 = [
		"这里有你的百宝袋和成就记录（左上角），可以通过查看成就来决定下一步去哪里。",
		"",
	];
	const dialogues1 = [
		"（大黄把我带到这里应该是要完成什么任务。）",
		"你们在吵什么？不妨告诉我，我或许可以帮忙。",
		"是这样的，公子，我家三个儿子如今到了成家立业的年纪，今天我把家里的田地分给他们，可他们认为我分配不均，这才吵了起来。",
		"您先别急，我或许可以帮您证明。",
		"",
	];
	const dialogues2 = ["多谢公子，这下可算证明我没有偏心了。", ""];
	const dialogues3 = [
		"公子，在下还有一事相求。我的地是三角形的，如今我想买一些高粱种子种在篱笆处，现下不知篱笆处有多长，不知该买多少种子。",
		"好说。",
		"",
	];
	const dialogues4 = [
		"真是妙哉，请问公子是如何解出的？",
		"可听说赵爽弦图？当直角三角形一条直角边“勾”等于3，另一条直角边“股”等于4的时候，那么它的斜边“弦”就必定是5。这个原理为大禹治水时总结出来的。",
		"公子可真是见多识广，多谢公子，有些东西还请公子收下。",
		"",
	];
	const dialogues5 = [
		"让我看看完成了哪些成就了。（点击成就即可跳转对应场景）",
	];

	// 以下两个变量需要根据狗的实际图片大小进行调整
	const dogWidth = 100;
	const dogHeight = 80;

	// 定义人物点击事件处理函数
	const handleCharacterClick = () => {
		if (isFainted) {
			setIsFainted(false);
		}
	};
	const preventArrowKeyScroll = e => {
		if ([37, 38, 39, 40].includes(e.keyCode)) {
			e.preventDefault();
		}
	};
	let animations = [];
	if (dogRunning) animations.push("running");
	// 使用 filter 来移除 'running' 动画类
	if (!dogRunning)
		animations = animations.filter(animation => animation !== "running");
	if (dogGoingHome) {
		animations.push("goingHome");
	}
	// 使用 filter 来移除 'goingHome' 动画类
	if (!dogGoingHome) {
		animations = animations.filter(animation => animation !== "goingHome");
	}
	// 使用 useEffect 钩子设置狗的位置
	useEffect(() => {
		if (
			characterPosition.x - 0.6 * screenWidth <= 80 &&
			characterPosition.y - 0.68 * screenHeight <= 20 &&
			diaglog1_undone
		) {
			setDialog1(true);
		}
		// 设置 CSS 变量
		document.documentElement.style.setProperty(
			"--screen-width",
			`${screenWidth}px`
		);
		document.documentElement.style.setProperty(
			"--screen-height",
			`${screenHeight}px`
		);

		// 获取游戏容器元素和角色元素
		const gameContainer = document.querySelector(".game-container");
		const character = document.querySelector(".character");
		const { x, y } = characterPosition;
		// 如果游戏容器元素和角色元素都存在
		if (gameContainer && character) {
			// 计算居中视角的滚动位置
			const scrollLeft = x - window.innerWidth / 2;
			const scrollTop = y - (window.innerHeight - initPositionY / 3) / 2;

			// 设置滚动位置
			// 设置滚动行为改为平滑的滚动

			window.scrollTo({
				left: scrollLeft,
				top: scrollTop,
			});
		}
		const radius = 150;
		setDistance1Length(
			Math.sqrt(
				Math.pow(x - xBrother1Length, 2) +
					Math.pow(y - yBrother1Length, 2)
			)
		);

		setDistance1Width(
			Math.sqrt(
				Math.pow(x - xBrother1Width, 2) +
					Math.pow(y - yBrother1Width, 2)
			)
		);

		setDistance2Height(
			Math.sqrt(
				Math.pow(x - xBrother2Height, 2) +
					Math.pow(y - yBrother2Height, 2)
			)
		);

		setDistance2Width(
			Math.sqrt(
				Math.pow(x - xBrother2Width, 2) +
					Math.pow(y - yBrother2Width, 2)
			)
		);

		setDistance3Height(
			Math.sqrt(
				Math.pow(x - xBrother3Height, 2) +
					Math.pow(y - yBrother3Height, 2)
			)
		);

		setDistance3UpWidth(
			Math.sqrt(
				Math.pow(x - xBrother3UpWidth, 2) +
					Math.pow(y - yBrother3UpWidth, 2)
			)
		);

		setDistance3BottomWidth(
			Math.sqrt(
				Math.pow(x - xBrother3BottomWidth, 2) +
					Math.pow(y - yBrother3BottomWidth, 2)
			)
		);
		if (!dialog1 && !dialogVisible && !diaglog1_undone) {
			if (distance1Length <= radius) {
				setShowCardBrother1Length(true);
			}
			if (distance1Width <= radius) {
				setShowCardBrother1Width(true);
			}
			if (distance2Height <= radius) {
				setShowCardBrother2Height(true);
			}
			if (distance2Width <= radius) {
				setShowCardBrother2Width(true);
			}
			if (distance3Height <= radius) {
				setShowCardBrother3Height(true);
			}
			if (distance3UpWidth <= radius) {
				setShowCardBrother3UpWidth(true);
			}
			if (distance3BottomWidth <= radius) {
				setShowCardBrother3BottomWidth(true);
			}
		}

		if (
			showCardBrother1Width &&
			setShowCardBrother1Length &&
			showCardBrother2Height &&
			showCardBrother2Width &&
			showCardBrother3UpWidth &&
			showCardBrother3BottomWidth &&
			showCardBrother3Height
		) {
			setTimeout(() => {
				setGame(true);
			}, 300);
		}

		if (
			inputBrother1 == 600 &&
			inputBrother2 == 600 &&
			inputBrother3 == 600
		) {
			setTimeout(() => {
				setGame(false);
				setDialog2(true);
			}, 300);
		}
		const dogStopX = initPositionX - dogWidth / 2;
		const dogStopY = initPositionY + dogHeight / 2;

		// 设置 CSS 变量
		document.documentElement.style.setProperty(
			"--dog-stop-x",
			`${dogStopX}px`
		);
		document.documentElement.style.setProperty(
			"--dog-stop-y",
			`${dogStopY}px`
		);

		window.addEventListener("keydown", preventArrowKeyScroll);

		// useEffect 的清理函数在组件卸载时执行，用来移除事件监听
		return () => {
			window.removeEventListener("keydown", preventArrowKeyScroll);
		};
	}, [
		characterPosition.x,
		characterPosition.y,
		inputBrother1,
		inputBrother2,
		inputBrother3,
	]);
	return (
		<div
			className="game-container backgroundImage"
			style={{ backgroundImage: `url(${backgroundImage})` }}
		>
			<Map/>
			<TreasureBox />
			<AchievementList
				achievementId={3}
				handleClick={
					finished
						? () => {
								history.push("/p1/DeclineChapterScene");
							}
						: () => {}
				}
			/>
			<Character
				characterImage={characterImage}
				characterImages={characterImages}
				isFainted={isFainted}
				onCharacterClick={handleCharacterClick}
				canMove={canMove}
				initPositionX={initPositionX}
				initPositionY={initPositionY}
				onPositionChange={handlePositionChange}
				ifProtagonist="true"
			/>

			<Dog
				ref={dogRef}
				initialPositionX={dogX}
				initialPositionY={dogY}
				animations={animations}
				visible={dogVisible}
			/>
			<Card
				visible={showCard}
				onClick={() => {
					setShowCard(false);
					setDialog1_1(true);
				}}
			>
				<p>获得伙伴</p>
				<p>大黄</p>
			</Card>
			<Card
				size={{ width: "300px", height: "100px" }}
				fontSize={"25px"}
				visible={showTreasure}
				background={"white"}
				onClick={() => {
					setShowTreasure(false);
					setDialog5(true);
				}}
			>
				<p>获得物品 </p>
				<p>算筹</p>
			</Card>
			{game && (
				<div className="fieldGame">
					<div>
						老大：
						<input
							value={inputBrother1}
							onChange={e => setInputBrother1(e.target.value)}
						/>
						平方步
					</div>
					<div>
						老二：
						<input
							value={inputBrother2}
							onChange={e => setInputBrother2(e.target.value)}
						/>
						平方步
					</div>
					<div>
						老三：
						<input
							value={inputBrother3}
							onChange={e => setInputBrother3(e.target.value)}
						/>
						平方步
					</div>
				</div>
			)}
			<div
				className="ground"
				style={{
					display: showCardBrother1Length ? "flex" : "none",
					left: xBrother1Length,
					top: yBrother1Length,
				}}
			>
				<p>30步</p>
			</div>
			<div
				className="ground"
				style={{
					display: showCardBrother1Width ? "flex" : "none",
					left: xBrother1Width,
					top: yBrother1Width,
				}}
			>
				<p>20步</p>
			</div>
			<div
				className="ground"
				style={{
					display: showCardBrother2Height ? "flex" : "none",
					left: xBrother2Height,
					top: yBrother2Height,
				}}
			>
				<p>40步</p>
			</div>
			<div
				className="ground"
				style={{
					display: showCardBrother2Width ? "flex" : "none",
					left: xBrother2Width,
					top: yBrother2Width,
				}}
			>
				<p>30步</p>
			</div>
			<div
				className="ground"
				style={{
					display: showCardBrother3UpWidth ? "flex" : "none",
					left: xBrother3UpWidth,
					top: yBrother3UpWidth,
				}}
			>
				<p>8步</p>
			</div>
			<div
				className="ground"
				style={{
					display: showCardBrother3BottomWidth ? "flex" : "none",
					left: xBrother3BottomWidth,
					top: yBrother3BottomWidth,
				}}
			>
				<p>12步</p>
			</div>
			<div
				className="ground"
				style={{
					display: showCardBrother3Height ? "flex" : "none",
					left: xBrother3Height,
					top: yBrother3Height,
				}}
			>
				<p>60步</p>
			</div>
			{gouGuVisible && (
				<div className="gouguGame">
					<div style={{ marginBottom: "80px" }}>二哥篱笆处地长</div>
					<div className="gouGu">
						<div>37步</div>
						<div>45步</div>
						<div
							onClick={() => {
								setGouGuVisible(false);
								setGouGuSuccess(true);
							}}
						>
							50步
						</div>
					</div>
				</div>
			)}

			{showChatBubble && <div className="chat-bubble">争吵声</div>}
			{!isFainted && dialogVisible && (
				<Dialog
					dialogues={dialogues}
					backgroundImage={dialogImage}
					triggerIndexEvents={[2, 3]}
					eventHandlers={[
						() => {
							setTimeout(() => {
								setDogVisible(true);
								setDogRunning(true);
							}, 2500);
						},
						() => {
							setShowCard(true);
							setDialogVisible(false);
						},
					]}
					dialogueImages={[
						{ leftImage: protagonistImage },
						{},
						{},
						{},
					]}
				/>
			)}
			{dialog1_1 && (
				<Dialog
					dialogues={dialogues1_1}
					backgroundImage={dialogImage}
					triggerIndexEvents={[0, 1]}
					eventHandlers={[
						() => {
							setShowCard(false);
						},
						() => {
							setDialog1_1(false);
							setCanMove(true);
							setDogGoingHome(true);
							setShowChatBubble(true);
						},
					]}
					dialogueImages={[{}]}
				/>
			)}
			{dialog1 && (
				<Dialog
					dialogues={dialogues1}
					backgroundImage={dialogImage}
					triggerIndexEvents={[4]}
					eventHandlers={[
						() => {
							setDialog1(false);
							setDialog1_undone(false);
						},
					]}
					dialogueImages={[
						{ leftImage: protagonistImage },
						{ leftImage: protagonistImage },
						{ rightImage: familyHeadLeftImage },
						{ leftImage: protagonistImage },
					]}
				/>
			)}
			{dialog2 && (
				<Dialog
					backgroundImage={dialogImage}
					dialogues={dialogues2}
					triggerIndexEvents={[1]}
					eventHandlers={[
						() => {
							setDialog2(false);
							setFieldSuccess(true);
						},
					]}
					dialogueImages={[{ rightImage: familyHeadLeftImage }, {}]}
				/>
			)}
			{dialog3 && (
				<Dialog
					backgroundImage={dialogImage}
					dialogues={dialogues3}
					triggerIndexEvents={[2]}
					eventHandlers={[
						() => {
							setDialog3(false);
							setTimeout(() => {
								setGouGuVisible(true);
							}, 200);
						},
					]}
					dialogueImages={[
						{ rightImage: brother2LeftImage },
						{ leftImage: protagonistImage },
						{ leftImage: protagonistImage },
						{ rightImage: brother2LeftImage },
						{ leftImage: protagonistImage },
						{ leftImage: protagonistImage },
					]}
				/>
			)}
			{dialog4 && (
				<Dialog
					backgroundImage={dialogImage}
					dialogues={dialogues4}
					triggerIndexEvents={[3]}
					eventHandlers={[
						() => {
							setShowTreasure(true);
							setGouGuVisible(false);
							setDialog4(false);
							dispatch({
								type: "treasureBox/showItem",
								payload: 3,
							});
						},
					]}
					dialogueImages={[
						{ rightImage: brother2LeftImage },
						{ leftImage: protagonistImage },
						{ rightImage: brother2LeftImage },
					]}
				/>
			)}
			{dialog5 && (
				<Dialog
					backgroundImage={dialogImage}
					dialogues={dialogues5}
					triggerIndexEvents={[0]}
					eventHandlers={[
						() => {
							setFinished(true);
						},
					]}
					dialogueImages={[{ leftImage: protagonistImage }]}
				/>
			)}
			{fieldSuccess && (
				<Card
					visible={true}
					cardId={1}
					onClick={() => {
						setDialog3(true);
						setFieldSuccess(false);
					}}
				>
					<p>获得成就</p>
					<p>方田</p>
				</Card>
			)}
			{gouGuSuccess && (
				<Card
					visible={true}
					cardId={2}
					onClick={() => {
						setGouGuSuccess(false);
						setDialog4(true);
					}}
				>
					<p>获得成就</p>
					<p>勾股</p>
				</Card>
			)}
		</div>
	);
};

export default connect(() => {})(FieldChapterScene);
